package com.imooc.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.imooc.pojo.SaveModel;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class URLFecter {

    private static final String HTTP = "http:";
    private static final String HTTPS = "https:";

    /**
     * get接口
     *
     * @param url
     * @param header
     * @return
     * @throws Exception
     */
    public static JSONObject getMethod(String url, Map<String, String> header) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpResponse response = HTTPUtils.getRawHtml(httpclient, url, header);
        JSONObject object = new JSONObject();
        //获取响应状态码
        int StatusCode = response.getStatusLine().getStatusCode();
        //如果状态响应码为200，则获取html实体内容或者json文件
        if (StatusCode == 200) {
            String entity = EntityUtils.toString(response.getEntity(), "utf-8");
            object = JSONObject.parseObject(entity);
            EntityUtils.consume(response.getEntity());
        } else {
            //否则，消耗掉实体
            EntityUtils.consume(response.getEntity());
        }
        return object;
    }

    private static String[] imageNames = {"111", "222", "333", "444", "555", "666", "777", "888", "999"};

    public static List<SaveModel> URLParser(Map<String, String> header, String url, String productId, String procectId) throws Exception {
        List<SaveModel> list = new ArrayList<>();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        RequestConfig defaultConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        httpGet.setConfig(defaultConfig);
        // 模拟浏览器浏览（user-agent的值可以通过浏览器浏览，查看发出请求的头文件获取）
        httpGet.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36");
        HttpResponse response = HTTPUtils.getRawHtml(httpclient, url, header);
        // 获取响应状态码
        int statusCode = response.getStatusLine().getStatusCode();
        try {
            HttpEntity entity = response.getEntity();
            // 如果状态响应码为200，则获取html实体内容或者json文件
            if (statusCode == 200) {
                String html = EntityUtils.toString(entity, Consts.UTF_8);

                System.out.println("+++++++++++++++++++++++++++++++++++++++" + url);
//                // 提取HTML得到商品信息结果
//                // 通过浏览器查看商品页面的源代码，找到信息所在的div标签，再对其进行一步一步地解析,这都需要对html代码进行分析了
                // 提取HTML得到商品信息结果
                Document doc = Jsoup.parse(html);
                // 通过浏览器查看商品页面的源代码，找到信息所在的div标签，再对其进行一步一步地解析,这都需要对html代码进行分析了

                Elements e = doc.getElementsByTag("script");
                JSONObject jsonObject;

                SaveModel saveModel;
                StringBuffer colors = new StringBuffer();
                StringBuffer size = new StringBuffer();
                String firstImageUrl;
                JSONArray optionRows;
                JSONObject option;
                String path;
                for (Element element : e) {
                    String jsons = element.data();
                    if (jsons.contains("function")) {
                        String sdpIssueTypes[] = jsons.split("exports.sdpIssueTypes");
                        for (String s1 : sdpIssueTypes) {
                            if (s1.contains("function(exports)")) {
                                saveModel = new SaveModel();
                                jsonObject = JSONObject.parseObject(s1.split("exports.sdp")[1].replaceFirst("=", "").replaceFirst(";", ""));
                                saveModel.setName(jsonObject.getString("title"));
                                saveModel.setUrl(url);
                                saveModel.setId(jsonObject.getString("productId"));
                                path = System.getProperty("user.dir") + "\\download\\" + procectId + "\\" + productId + "\\";
                                FileUtils.mkdirs(path);

                                if (jsonObject.containsKey("options") && null != jsonObject.getJSONObject("options")) {
                                    optionRows = jsonObject.getJSONObject("options").getJSONArray("optionRows");

                                    for (Object optionRow : optionRows) {
                                        option = JSON.parseObject(optionRow.toString());
                                        JSONArray attributes = option.getJSONArray("attributes");
                                        if (option.containsKey("sizeAttribute") && option.getBoolean("sizeAttribute")) {
                                            // 尺寸
                                            for (Object object : attributes) {
                                                size.append(JSON.parseObject(object.toString()).getString("name")).append(",");
                                            }
                                        } else {
                                            // 颜色
                                            for (Object object : attributes) {
                                                if (JSON.parseObject(object.toString()).containsKey("image") && null != JSON.parseObject(object.toString()).getString("image") && !"null".equals(JSON.parseObject(object.toString()).getString("image"))) {
                                                    firstImageUrl = HTTPS + JSON.parseObject(object.toString()).getJSONObject("image").getString("origin");
                                                    FileUtils.downLoadImage(path + JSON.parseObject(object.toString()).getString("name") + ".jpg", firstImageUrl);
                                                }
                                                colors.append(JSON.parseObject(object.toString()).getString("name")).append(",");
                                            }
                                        }
                                    }

                                    for (int i = 0; i < jsonObject.getJSONArray("images").size() && i < 9; i++) {
                                        FileUtils.downLoadImage(path + imageNames[i] + ".jpg", HTTPS + jsonObject.getJSONArray("images").getJSONObject(i).getString("origin"));
                                    }
                                } else {
//                                    JSONArray images = jsonObject.getJSONArray("images");
                                    for (int i = 0; i < jsonObject.getJSONArray("images").size() && i < 9; i++) {
                                        FileUtils.downLoadImage(path + imageNames[i] + ".jpg", HTTPS + jsonObject.getJSONArray("images").getJSONObject(i).getString("origin"));
                                    }
                                }
                                saveModel.setSize(size.toString());
                                saveModel.setColor(colors.toString());
                                JSONObject priceJson = jsonObject.getJSONArray("quantityBase").getJSONObject(0).getJSONObject("price");
                                saveModel.setPrice(priceJson.getString("salePrice"));
                                list.add(saveModel);
                            }

                        }
                    }
                }
                // 消耗掉实体
                EntityUtils.consume(response.getEntity());
            } else {
                // 消耗掉实体
                EntityUtils.consume(response.getEntity());
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return list;
    }

    public static List<String> urlParseImage(String html) {
        Document doc = Jsoup.parse(html);
        Elements ulList = doc.getElementsByTag("img");
        List<String> images = new ArrayList<>();
        for (Element item : ulList) {
            images.add(item.attr("src"));
        }
        return images;
    }


    public static Document parserUrl(Map<String, String> header, String url, String productId, String procectId) throws Exception {
        List<SaveModel> list = new ArrayList<>();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        RequestConfig defaultConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        httpGet.setConfig(defaultConfig);
        // 模拟浏览器浏览（user-agent的值可以通过浏览器浏览，查看发出请求的头文件获取）
        httpGet.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36");
        HttpResponse response = HTTPUtils.getRawHtml(httpclient, url, header);
        // 获取响应状态码
        int statusCode = response.getStatusLine().getStatusCode();
        Document doc = null;
        try {
            HttpEntity entity = response.getEntity();
            // 如果状态响应码为200，则获取html实体内容或者json文件
            if (statusCode == 200) {
                String html = EntityUtils.toString(entity, Consts.UTF_8);

                System.out.println("+++++++++++++++++++++++++++++++++++++++" + url);
//                // 提取HTML得到商品信息结果
//                // 通过浏览器查看商品页面的源代码，找到信息所在的div标签，再对其进行一步一步地解析,这都需要对html代码进行分析了
                // 提取HTML得到商品信息结果
                doc = Jsoup.parse(html);
                // 通过浏览器查看商品页面的源代码，找到信息所在的div标签，再对其进行一步一步地解析,这都需要对html代码进行分析了
                
                // 消耗掉实体
                EntityUtils.consume(response.getEntity());
            } else {
                // 消耗掉实体
                EntityUtils.consume(response.getEntity());
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return doc;
    }
}